<?php
/**
 * SERVICE 基类
 *
 * User: kaikaic
 * Date: 2018/4/20
 * Time: 15:29
 */

namespace service;

use think\Db;
use think\Log;

abstract class BasicService {

    const PAGE_SIZE = 10;

    private static $instance;

    private function __construct() {}

    public static function getInstance() {
        $className =  get_called_class();

        if (self::$instance == null || !is_a(self::$instance, $className)) {
            self::$instance = new $className();
            self::$instance->init();
        }

        return self::$instance;
    }

    protected abstract function init();

    protected $dataTable;

    /**
     * 查询
     */
    public function select($condition, $tableIndex=0, $order="") {
        $db = Db::name($this->dataTable[$tableIndex])->where($condition);
        if ($order) {
            $db->order($order);
        }

        return $db->select();
    }
    /**
     * 查询
     */
    public function selectlimit($condition, $tableIndex=0, $order="",$limit="") {
        $db = Db::name($this->dataTable[$tableIndex])->where($condition);
        if ($order) {
            $db->order($order);
        }
        if($limit){
            $db->limit($limit);
        }

        return $db->select();
    }
    /**
     * 读取单条信息
     * @params $column=字段名
     */
    public function find($recordID, $column='id', $tableIndex=0) {
        $record = Db::name($this->dataTable[$tableIndex])->where($column, $recordID)->find();

        return $record;
    }

    /**
     * 读取单条记录
     */
    public function single($condition, $tableIndex=0) {
        return Db::name($this->dataTable[$tableIndex])->where($condition)->find();
    }

    /**
     * 写入新纪录
     */
    public function insert($data, $tableIndex=0) {
        return Db::name($this->dataTable[$tableIndex])->insertGetId($data);
    }

    /**
     * 更新记录
     */
    public function update($data, $key, $column='id', $tableIndex=0) {
        return Db::name($this->dataTable[$tableIndex])->where($column, $key)->update($data);
    }

    /**
     * 删除记录
     */
    public function remove($where, $tableIndex=0) {
        return Db::name($this->dataTable[$tableIndex])->where($where)->delete();
    }

    /**
     * 记录请求日志
     */
    protected static function logger($message) {
        Log::record($message, Log::DEBUG);
        Log::save();
    }
}
